//
//  MSShowerVC.m
//  MS
//
//  Created by He Yuan on 13-2-6.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSShowerVC.h"
#import "CustomSegmentedControl.h"
#import "EGORefreshTableHeaderView.h"

#import "UIButton+WebCache.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "MSShowerCell.h"

#import "MSPictureDetailVC.h"

#import "MSShowerDetailVC.h"

#import "MSUserHomeVC.h"

@interface MSShowerVC ()<CustomSegmentedControlDelegate,EGORefreshTableHeaderDelegate, UITableViewDelegate, UITableViewDataSource,UIScrollViewDelegate>
{
    UITableView  *showerTableView;
    
    BOOL _reloading;
    
    EGORefreshTableHeaderView *_refreshHeaderView;
    
    BOOL isNextPage;
}

@property(nonatomic,retain)NSMutableArray *dataArr;

@property(nonatomic,retain)UITableView  *showerTableView;

- (void)reloadTableViewDataSource;
- (void)doneLoadingTableViewData;

@end

@implementation MSShowerVC
@synthesize showerTableView = _showerTableView;
@synthesize dataArr = _dataArr;


- (id)init
{
    self = [super init];
    if (self)
    {
        // Custom initialization
        
        _dataArr = [[NSMutableArray alloc]initWithObjects:nil,nil];
        
    }
    
    return self;
}



-(void)loadView
{
    [super loadView];
    
    _showerTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _showerTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _showerTableView.delegate = self;
    _showerTableView.dataSource = self;
    _showerTableView.backgroundColor = [UIColor clearColor];
    _showerTableView.backgroundView = nil;
    [self.view addSubview:_showerTableView];
    
    //custom segment
    NSDictionary *item1 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"精选"),@"title",@"s1",@"img", nil];
    NSDictionary *item2 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"同城"),@"title",@"s2",@"img", nil];
    NSDictionary *item3 = [NSDictionary dictionaryWithObjectsAndKeys:HYLocalizedString(@"关注"),@"title",@"s3",@"img", nil];
    NSArray *items = [NSArray arrayWithObjects:item1,item2,item3, nil];
    CustomSegmentedControl *segment = [[CustomSegmentedControl alloc]initWithFrame:CGRectZero items:items defaultSelectIndex:0];
    segment.delegate = self;
    self.navigationItem.titleView=segment;
    
    if (_refreshHeaderView == nil)
    {
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.showerTableView.bounds.size.height, self.view.frame.size.width, self.showerTableView.bounds.size.height)];
		_refreshHeaderView.delegate = self;
		[self.showerTableView addSubview:_refreshHeaderView];
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:NO];
    HYLog(@"viewWillAppear");
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad
{
//    [self setTitle:@"我型我秀" showBackButton:NO];

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];

    [self performSelector:@selector(ViewFrashData) withObject:nil afterDelay:0.6];
}

-(NSString *)formatTime:(NSString *)ctime
{
    NSRange range = [ctime rangeOfString:@"年"];
    if (range.location != NSNotFound)
    {
        if (range.location+1>= [ctime length])return ctime;
        return  [ctime substringFromIndex:range.location+1];
    }
    return ctime;
}

-(void)ViewFrashData
{
    [_showerTableView setContentOffset:CGPointMake(0,-75) animated:YES];
    [self performSelector:@selector(doneManualRefresh) withObject:nil afterDelay:0.4];
}

-(void)doneManualRefresh
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self.showerTableView];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.showerTableView];
}

-(void)requestData
{    
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithInt:1],@"hot",
                        [NSNumber numberWithInteger:1],@"page",
                        nil];    
    [WebService  getRequestAction:APIEveryOneList
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             HYLog(@"%@",info);
             if (info) {
                 isNextPage = [[info objectForKey:@"nextpage"] boolValue];
                 [_dataArr addObjectsFromArray:[info objectForKey:@"result"]];
                 [self.showerTableView reloadData];
                 [self.showerTableView flashScrollIndicators];
             }
         }
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
     } progress:nil];
}

#pragma CustomSegmentedControlDelegate methord
-(void)didSelectIndex:(NSUInteger)selectedIndex withSegmentControl:(CustomSegmentedControl*)segmentControl
{
    //    HYLog(@"%d",selectedIndex);
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource
{
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
    [self requestData];
}

- (void)doneLoadingTableViewData
{
	//  model should call this when its done loading
	_reloading = NO;
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setValue:date forKey:@"EGORefreshTableView_MSShower_LastRefresh"];
    [[NSUserDefaults standardUserDefaults] synchronize];
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.showerTableView];	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
    NSDate *date =  [[NSUserDefaults standardUserDefaults] valueForKey:@"EGORefreshTableView_MSShower_LastRefresh"];
    if (date == nil)date = [NSDate date];
	return date; // should return date data source was last changed
    
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArr count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat baseHeight = 297+44;
    return baseHeight + CELL_TXTLBL_HEIGHT([[_dataArr objectAtIndex:indexPath.row] objectForKey:@"content"]);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
   __block MSShowerCell *cell = (MSShowerCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[MSShowerCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    [cell.avatarButton setImageWithURL:[NSURL URLWithString:[item objectForKey:@"avatar"]] forState:UIControlStateNormal];
    [cell.avatarButton addTarget:self action:@selector(userHomePage:) forControlEvents:UIControlEventTouchUpInside];
    [cell.avatarFlagButton setBackgroundImage:[UIImage imageNamed:@"shower_avatar_tag"] forState:UIControlStateNormal];
    [cell.aliasLbl setText:[item objectForKey:@"user_name"]];
    NSString *address = [item objectForKey:@"address"]==nil?@"未知":[item objectForKey:@"address"];
    [cell.addressLbl setText:address];
    [cell.imageAndTxtView setText:[item objectForKey:@"content"]];
    [cell.imageAndTxtView setContentImage:[item objectForKey:@"thumb"]];
    [cell.timeLbl setText:[self formatTime:[item objectForKey:@"create_time"]]];
    [cell.commentCountLbl setText:[item objectForKey:@"comment_count"]];
    [cell.likeCountLbl setText:[item objectForKey:@"collect_count"]];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MSShowerDetailVC *vc  = [[MSShowerDetailVC alloc]initWithDatas:_dataArr currentIndex:indexPath.row];
    [vc setHidesBottomBarWhenPushed:YES];
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:YES];
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)userHomePage:(UIButton *)btn
{
    MSShowerCell *cell = (MSShowerCell *)btn.superview.superview;
    NSIndexPath *indexPath = [self.showerTableView indexPathForCell:cell];
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    MSUserHomeVC *vc = [[MSUserHomeVC alloc]initWithUID:[item objectForKey:@"uid"] userName:[item objectForKey:@"user_name"]];
    [vc setHidesBottomBarWhenPushed:YES];
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:YES];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidUnload {
	_refreshHeaderView=nil;
    self.showerTableView = nil;
}

- (void)dealloc
{
    self.showerTableView = nil;
	_refreshHeaderView = nil;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
